<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/7/17 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------


namespace app\common\subscribes;

use app\api\service\HaiDing;

use app\api\service\MarketingService;
use app\api\service\MemberService;
use app\common\model\tang\Cost;
use app\common\model\tang\CostType;
use app\common\model\tang\Merchant;
use app\common\model\tang\MerchantList;
use think\cache\driver\Redis;

class MerchantSubscribe extends Base
{
    /**
     * 定时执行的方法
     */
    public function onMerchant()
    {
        //重置商户信息
        $company = new MerchantList();
        $HDService = new HaiDing();
//        $result = $HDService->getMerchant(0, 0);
//        if (!empty($result)) {
//            foreach ($result as $k => $v) {
//                $res['merchant_sn'] = $v['code'];
//                $res['merchant_uuid'] = $v['uuid'];
//                $res['tenant_name'] = $v['name'];
//                $res['short_name'] = $v['shortName'];
//                $res['foreign_name'] = $v['foreignName'];
//                $res['short_foreign_name'] = $v['shortForeignName'];
//                $res['signing_company'] = $v['name'];
//                $res['state'] = $v['state'];
//                $res['type'] = $v['type'];
//                $res['contactor'] = isset($v['contactInfos'][0]['contactor']) ?? '';
//                $res['brand_dealer_type'] = $v['brandDealerType'];
//                $res['create_time'] = time();
//                $isFirst = $company->where('merchant_sn', $v['code'])->find();
//                if (empty($isFirst)) {
//                    (new MerchantList())->save($res);
//                }
//            }
//
//        }
        $costModel = new Cost();
//        //获取合同信息
        $getContractInfo = (new HaiDing())->getContentInfo(0, 0);
        if (!empty($getContractInfo)) {
            foreach ($getContractInfo as $key => $val) {
                $mer = [];
                $mer['uuid'] = $val['uuid'];
                $mer['merchant_sn'] = $val['tenant']['code'];
                $mer['company'] = $val['tenant']['name'];
                $mer['username'] = $val['name'];
                $mer['code'] = $val['code'];
                $mer['name'] = $val['name'];
                $mer['contract_type'] = $val['contractType'];
                $mer['store_uuid'] = $val['store']['uuid'];
                $mer['store_code'] = $val['store']['code'];;
                $mer['store_name'] = $val['store']['name'];
                $mer['tenant_uuid'] = $val['tenant']['uuid'];
                $mer['tenant_code'] = $val['tenant']['code'];
                $mer['tenant_name'] = $val['tenant']['name'];
                $mer['positions_uuid'] = $val['positions'][0]['uuid'];
                $mer['positions_code'] = $val['positions'][0]['code'];
                $mer['positions_name'] = $val['positions'][0]['name'];
                $mer['start_time'] = strtotime($val['beginDate']);
                $mer['end_time'] = strtotime($val['endDate']);
                $mer['biz_state'] = $val['bizState'];
                $mer['rent_area'] = $val['rentArea'];
                $mer['create_time'] = time();
                $exist = (new Merchant())->where('code', $val['code'])->find();
                if ($exist) {
                    (new Merchant())->update(['biz_state' => $val['bizState']], ['id' => $exist['id']]);
                }
                if ($val['store']['code'] == '401001' && $val['bizState'] != 'canceled') {
                    if (!empty($val['name']) && $val['name'] != '-') {
                        $brandInfo = (new HaiDing())->getBrand(0, 0, $val['name']);
                        if (!empty($brandInfo)) {
                            foreach ($brandInfo as $kkk => $vvv) {
                                if($vvv['name']==$val['name']){
                                $mer['brand_code'] = $brandInfo[$kkk]['code'];
                                $mer['bizType_code'] = $brandInfo[$kkk]['bizType']['code'];
                                $mer['bizType_name'] = $brandInfo[$kkk]['bizType']['name'];
                            }
                        }

                    }

                }
                $isFirst = (new Merchant())->where('code', $val['code'])->find();
                if (empty($isFirst)) {
                    $mer['password'] = md5(123456);
                    $merchant_list_id = $company->where('merchant_sn', $val['tenant']['code'])->value('id');
                    $mer['merchant_list_id'] = $merchant_list_id;
                    $mer['positionType'] = $val['positionType'];
                    (new Merchant())->save($mer);
                } else {
                    $merchant_list_id = $company->where('merchant_sn', $val['tenant']['code'])->value('id');
                    $mer['merchant_list_id'] = $merchant_list_id;
                    (new Merchant())->where('uuid', $val['uuid'])->save($mer);
                    if ($val['bizState'] != 'stopped' || $val['bizState'] != 'canceled') {
                        // 会员系统接口请求
                        $isFirst = $isFirst->toArray();
                        $Member = new MemberService();
                        if (!empty($isFirst['name']) || $isFirst['name'] != '-') {
                            $MemberId = $Member->pushMerchant($isFirst);
                            if (is_numeric($MemberId)) {
                                (new Merchant())->where('uuid', $val['uuid'])->save(['member_id' => $MemberId]);
                            }
                        }
                        $Marketing = new MarketingService();
                        if (empty($isFirst['marketing_id'])) {
                            //支付营销系统新增请求
                            $MarkResult = $Marketing->addSubMch($isFirst);
                            if (isset($MarkResult['id'])) {
                                (new Merchant())->where('uuid', $val['uuid'])->save(['marketing_id' => $MarkResult['id']]);
                            }
                        }
                        $merchant_id = 0;
                        $merchant_id = (new Merchant())->where('uuid', $val['uuid'])->value('id');
                        if ($merchant_id) {
                            if ($val['depositTerms']) {
                                foreach ($val['depositTerms'] as $de => $ve) {
                                    foreach ($ve['details'] as $value => $item) {
                                        $costInfo = [];
                                        $isfirst = [];
                                        if ($item['amount'] > 0) {
                                            $costType_id = (new CostType())->where('cost_type_id', $item['subject']['code'])->value('id');
                                            if ($costType_id) {
                                                $costInfo['merchant_id'] = $merchant_id;
                                                $costInfo['start_time'] = strtotime($val['beginDate']);
                                                $costInfo['end_time'] = strtotime($val['endDate']);
                                                $costInfo['all_amount'] = bcmul($item['amount'], 100);
                                                $costInfo['type'] = 1;
                                                $costInfo['cost_type_id'] = $costType_id;
                                                $costInfo['cost_name'] = $item['subject']['name'];
                                                $costInfo['cost_code'] = $item['subject']['code'];
                                                $costInfo['contract_uuid'] = $val['uuid'];
                                                $costInfo['contract_code'] = $val['code'];
                                                $isfirst = $costModel->where($costInfo)->find();
                                                if ($isfirst) {
                                                    $costInfo['pay_amount'] = bcmul($item['receivedAmount'], 100);
                                                    if ($item['amount'] == $item['receivedAmount']) {
                                                        if ($isfirst['pay_status'] == 0) {
                                                            $upInfo['bill_no'] = $this->getBill();
                                                            $upInfo['pay_time'] = date('Y-m-d H:i:s');
                                                        }
                                                        $upInfo['pay_status'] = 1;
                                                        $upInfo['amount'] = 0;
                                                    } else {
                                                        $upInfo['amount'] = bcsub(bcmul($item['amount'], 100), bcmul($item['receivedAmount'], 100));
                                                        $upInfo['pay_status'] = 0;
                                                    }
                                                    $costModel->update($upInfo, ['id' => $isfirst['id']]);
                                                } else {
                                                    $costInfo['pay_amount'] = bcmul($item['receivedAmount'], 100);
                                                    if ($item['amount'] == $item['receivedAmount']) {
                                                        $costInfo['pay_status'] = 1;
                                                        $costInfo['amount'] = 0;
                                                        $costInfo['pay_time'] = date('Y-m-d H:i:s');
                                                        $costInfo['bill_no'] = $this->getBill();;
                                                    } else {
                                                        $costInfo['amount'] = bcsub(bcmul($item['amount'], 100), bcmul($item['receivedAmount'], 100));
                                                        $costInfo['pay_status'] = 0;
                                                    }
                                                    $costInfo['order_sn'] = $this->OrderSn();
                                                    $costInfo['create_time'] = time();
                                                    $costModel->insert($costInfo);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }

            }

        }
    }
}

function OrderSn()
{
    $OrderSn = 'T' . date('Ymd', time()) . rand(10000, 99999);
    $model = new \app\common\model\tang\Cost();
    $is_sn = $model->where('order_sn', $OrderSn)->find();
    if ($is_sn) {
        $this->OrderSn();
    }
    return $OrderSn;
}

function getBill()
{
    $redis = (new Redis(config('queue.connections.redis')));
    $count = $redis->llen('HFZD' . date('Ymd'));
    $redis->delete('HFZD' . date('Ymd', strtotime('-1 day')));
    if ($count == 0) {
        for ($i = 99999; $i >= 0; $i--) {
            $jh = str_pad($i, 5, "0", STR_PAD_LEFT);
            $redis->lPush('HFZD' . date('Ymd'), $jh);
        }
    }
    $time = date('Ymd', time());
    $bill = 'HFZD' . $time . $redis->lpop('HFZD' . date('Ymd'));
    return $bill;
}
}